package com.ruoyi.pingan.fymodule.order.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.pingan.fymodule.account.entity.SxoSafetyUser;
import com.ruoyi.pingan.fymodule.account.service.ISxoSafetyUserService;
import com.ruoyi.pingan.fymodule.order.entity.SxoSafetyMemWithdrawal;
import com.ruoyi.pingan.fymodule.order.mapper.SxoSafetyMemWithdrawalMapper;
import com.ruoyi.pingan.fymodule.order.service.ISxoSafetyMemWithdrawalService;
import com.ruoyi.pingan.fymodule.sxosafetyaccountrecord.entity.SxoSafetyAccountRecord;
import com.ruoyi.pingan.fymodule.sxosafetyaccountrecord.service.SxoSafetyAccountRecordService;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.SingleTransactionStatusQueryDto;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.SingleTransactionStatusQueryVo;
import com.ruoyi.pingan.fymodule.thirdpa.service.PaBondService;
import com.qcloud.cos.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
*
* 平安分账会员提现 业务层实现
*
* @author wangy
* @since 2025-06-30
*/
@Slf4j
@Service
public class SxoSafetyMemWithdrawalServiceImpl extends ServiceImpl<SxoSafetyMemWithdrawalMapper, SxoSafetyMemWithdrawal> implements ISxoSafetyMemWithdrawalService {

    @Autowired
    private PaBondService paBondService;
    @Autowired
    private ISxoSafetyUserService sxoSafetyUserService;
    @Autowired
    private SxoSafetyAccountRecordService sxoSafetyAccountRecordService;

    @Override
    public void execute6110_6085(){
        log.info("提现状态查询；时间:{}", DateUtil.now());
        Date date = new Date();
        Date startTime = DateUtil.offsetDay(date, -1);
        //Date endTime = DateUtil.offsetMinute(date, -120);
        LambdaQueryWrapper<SxoSafetyMemWithdrawal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyMemWithdrawal::getCashStatus, 0);
        queryWrapper.notIn(SxoSafetyMemWithdrawal::getTranStatus, 0, 1);
        queryWrapper.orderByAsc(SxoSafetyMemWithdrawal::getId);
        List<SxoSafetyMemWithdrawal> lists = this.list(queryWrapper);
        if (lists.isEmpty()) {
            log.info("提现状态查询；时间:{};数量：{}", DateUtil.now(),0);
            return;
        }
        String dataStr = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        for (SxoSafetyMemWithdrawal withdrawal : lists) {
            try {
                SxoSafetyUser user = sxoSafetyUserService.getOne(new QueryWrapper<SxoSafetyUser>().lambda()
                        .eq(SxoSafetyUser::getSubAcctNo, withdrawal.getSubAcctNo()));
                if (Objects.isNull(user)) {
                    continue;
                }
                if (StrUtil.isEmpty(withdrawal.getJzbAcceptSeqNo())) {
                    continue;
                }
                SingleTransactionStatusQueryDto  dto = new SingleTransactionStatusQueryDto();
                if("1".equals(withdrawal.getTranType())){
                    dto.setFunctionFlag("3");
                }
                dto.setTranNetSeqNo(withdrawal.getCnsmrSeqNo());
                SingleTransactionStatusQueryVo vo = paBondService.singleTransactionStatusQuery(dto);
                if(!Objects.isNull(vo) && !StringUtils.isNullOrEmpty(vo.getTranStatus())){
                    SxoSafetyMemWithdrawal mod = new SxoSafetyMemWithdrawal();
                    mod.setId(withdrawal.getId());
                    mod.setTranStatus(Integer.valueOf(vo.getTranStatus()));
                    mod.setTranAmt(vo.getTranAmt());
                    if ("0".equals(vo.getTranStatus()) || "1".equals(vo.getTranStatus())){
                        if("0".equals(vo.getTranStatus())){
                            String tranDateStr = vo.getTranDate().concat(vo.getTranTime());
                            Date tranDate = DateUtil.parse(tranDateStr);
                            mod.setTranDate(DateUtil.format(tranDate, "yyyy-MM-dd HH:mm:ss"));
                        }else if("1".equals(vo.getTranStatus())){
                            mod.setErrorMsg(vo.getFailMsg());
                        }
                        mod.setUpdTime(dataStr);
                        this.updateById(mod);
                        if("1".equals(mod.getTranStatus())){
                            SxoSafetyAccountRecord record = sxoSafetyAccountRecordService.getOne(new QueryWrapper<SxoSafetyAccountRecord>().lambda()
                                    .eq(SxoSafetyAccountRecord::getOrderNo, withdrawal.getJzbAcceptSeqNo())
                                    .last("limit 1"));
                            if(Objects.isNull(record)){
                            }else{
                                BigDecimal balance = new BigDecimal(user.getBalance()).add(new BigDecimal(withdrawal.getCashAmt()));
                                sxoSafetyUserService.update(new UpdateWrapper<SxoSafetyUser>().lambda()
                                        .set(SxoSafetyUser::getBalance, balance.toString())
                                        .eq(SxoSafetyUser::getId, user.getId())
                                );
                                SxoSafetyAccountRecord accountRecord = new SxoSafetyAccountRecord();
                                accountRecord.setShopId(user.getShopId());
                                accountRecord.setBusinessType(1);
                                accountRecord.setOrderNo(withdrawal.getJzbAcceptSeqNo());
                                accountRecord.setChangeType(1);
                                accountRecord.setAmount(withdrawal.getCashAmt());
                                accountRecord.setFinalAmount(balance.toString());
                                accountRecord.setReason("提现失败");
                                accountRecord.setAddTime(mod.getUpdTime());
                                sxoSafetyAccountRecordService.saveOrUpdate(accountRecord);
                            }
                        }
                    }
                }
            }catch (Exception e){
                log.error("execute6110_6085执行异常：{}", e.getMessage());
            }
        }
        log.info("提现状态查询；时间:{}；数量：{}", DateUtil.now(), lists.size());
    }
}